import {
  tags_list,
  update_userInfo,
  update_userInfo_v4,
  ftp_file,
  baseUrl,
  del_file,
  del_user_img,
  get_carte
} from "../../utils/api.js"
import WxValidate from '../../utils/WxValidate'
const util = require('../../utils/util')
const {
  getTimeSeconds
} = util

// pages/editCarte/editCarte.js
const app = getApp()
const recorderManager = wx.getRecorderManager()
var innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    TaskShow: 0,
    FormList: [{
      title: '姓名',
      name: 'name',
      placeholder: '请填写姓名',
      type: 1
    },
    {
      title: '职位',
      name: 'position',
      placeholder: '请填写职位',
      type: 1
    },
    {
      title: '所属公司',
      name: 'company',
      placeholder: '请填写所属公司',
      type: 1
    },
    {
      title: '联系方式',
      name: 'mobile',
      placeholder: '请填写联系方式',
      type: 1
    },
    {
      title: '邮箱地址',
      name: 'email',
      placeholder: '请填写邮箱地址',
      type: 1
    },
    {
      title: '微信号',
      name: 'weixin',
      placeholder: '请填写微信号',
      type: 1
    },
    {
      title: '公司地址',
      name: 'address',
      placeholder: '请填写地址',
      type: 2
    },
    ],
    CompanyLogo: {
      type: 0,
      src: ''
    },
    ProfilePicture: {
      type: 0,
      src: ''
    },
    Recorder: {
      type: 0,
      src: '',
      temp: '',
      playStatus: 0
    },
    Introduce: {
      title: '文字简介',
      name: 'introduce',
      placeholder: '请填写文字简介(0-120字数)',
    },
    Videoimg: {
      type: 0,
      src: ''
    },
    Video: {
      type: 0,
      src: ''
    },
    Pictuer: {
      type: 0,
      srcList: []
    },
    cutimg:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.img){
      this.setData({
        cutimg: options.img
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('onshow')
    this.getUserInfo()
  },

  // 获取名片信息
  getCarteInfo: function (uid, v_id) {
    const that = this
    let p = new Promise((resolve, reject) => {
      try {
        app.HttpGetSend(
          get_carte, {
            uid: uid,
            v_id: v_id
          },
          function (res) {
            // console.log(res)
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              let userInfo = { ...res.data }
              app.globalData.userInfo = userInfo
              that.setData({
                userInfo
              })
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify(userInfo)
              })
              // console.log(userInfo)
              resolve(userInfo)
            }
          })
      } catch (error) {
        console.log(error)
        reject(error)
      }
    })
    return p
  },

  // 获取用户信息 
  getUserInfo: function () {
    const that = this
    try {
      this.getCarteInfo(app.globalData.userInfo.id, app.globalData.userInfo.id).then(res => {
        let userInfo = res
        // console.log(userInfo)
        let checkNullEmptyUndefined = (aim) => {
          // console.log(typeof (aim) != 'undefined')
          // console.log(aim != 'undefined')
          if (aim != '' && aim != null && typeof (aim) != 'undefined' && aim != 'undefined') {
            return true
          } else {
            return false
          }
        }
        let changed = {}
        // 姓名
        if (checkNullEmptyUndefined(userInfo.name)) {
          changed['FormList[0].content'] = userInfo.name
        }
        // 职位
        if (checkNullEmptyUndefined(userInfo.position)) {
          changed['FormList[1].content'] = userInfo.position
        }
        // 所属公司
        if (checkNullEmptyUndefined(userInfo.company)) {
          changed['FormList[2].content'] = userInfo.company
        }
        // 联系方式
        if (checkNullEmptyUndefined(userInfo.mobile)) {
          // console.log(userInfo.mobile)
          changed['FormList[3].content'] = userInfo.mobile
        }
        // 邮箱地址
        if (checkNullEmptyUndefined(userInfo.email)) {
          changed['FormList[4].content'] = userInfo.email
        }
        // 微信号
        if (checkNullEmptyUndefined(userInfo.weixin)) {
          changed['FormList[5].content'] = userInfo.weixin
        }
        // 公司地址
        if (checkNullEmptyUndefined(userInfo.address)) {
          changed['FormList[6].content'] = userInfo.address
        }
        // 公司logo
        if (checkNullEmptyUndefined(userInfo.com_logo)) {
          changed['CompanyLogo.type'] = 1
          changed['CompanyLogo.src'] = userInfo.com_logo
        }
        // 个人形象照
        if (userInfo.img != '' && userInfo.img != null) {
          changed['ProfilePicture.type'] = 1
          changed['ProfilePicture.src'] = userInfo.img
        }
        // 语音简介
        if (userInfo.voice != '' && userInfo.voice != null) {
          changed['Recorder.type'] = 2
          changed['Recorder.src'] = userInfo.voice
          innerAudioContext.src = userInfo.voice
          changed['Recorder.duration'] = userInfo.length
          // try {
          //   // console.log(innerAudioContext.duration)
          //   // setTimeout(() => {
          //   //   console.log(innerAudioContext.duration)
          //   changed['Recorder.duration'] = changed['Recorder.duration'];
          //   // }, 1000)
          // } catch (error) {
          //   console.log(error)
          // }
        }
        // 文字简介
        if (checkNullEmptyUndefined(userInfo.introduce)) {
          changed['Introduce.content'] = userInfo.introduce
        }
        // 标签列表
        if (userInfo.flags.length > 0 && userInfo.flags != null) {
          this.getTagsList(userInfo.flags)
        } else {
          this.getTagsList()
        }
        // 视频img
        if (userInfo.video_img != null && userInfo.video_img != '') {
          // console.log(userInfo.files)
          changed['Videoimg.type'] = 1
          changed['Videoimg.src'] = userInfo.video_img
        }
        // 视频
        if (userInfo.video != '' && userInfo.video != null) {
          changed['Video.type'] = 1
          changed['Video.src'] = userInfo.video
        }
        // 照片
        if (userInfo.files.length > 0 && userInfo.files != null) {
          // console.log(userInfo.files)
          changed['Pictuer.type'] = 1
          changed['Pictuer.srcList'] = userInfo.files
        }
        this.setData({
          ...changed,
          userInfo
        })
      })
    } catch (error) {
      console.log(error)
    }
  },

  // 获取标签列表
  getTagsList: function name(aim_tags_list) {
    const that = this
    app.HttpGetSend(
      tags_list, {},
      function (res) {
        // console.log(res)
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          let TagsList = new Array(res.data.length)
          for (let i = 0; i < res.data.length; i++) {
            TagsList[i] = new Object()
            TagsList[i].id = res.data[i].id
            TagsList[i].content = res.data[i].title
            TagsList[i].status = 0
            TagsList[i].checked = false
            if (aim_tags_list) {
              for (let j = 0; j < aim_tags_list.length; j++) {
                if (res.data[i].id == aim_tags_list[j].flag_id) {
                  TagsList[i].status = 1
                  TagsList[i].checked = true
                }
              }
            }
          }
          that.setData({
            TagsList
          })
        }
      })
  },

  // 姓名输入
  nameInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[0].content'] = e.detail.value
    this.setData(changed)
  },

  // 姓名输入
  positionInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[1].content'] = e.detail.value
    this.setData(changed)
  },

  // 所属公司输入
  companyInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[2].content'] = e.detail.value
    this.setData(changed)
  },

  // 联系方式输入
  mobileInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[3].content'] = e.detail.value
    this.setData(changed)
  },

  // 邮箱地址输入
  emailInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[4].content'] = e.detail.value
    this.setData(changed)
  },

  // 微信号输入
  weixinInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[5].content'] = e.detail.value
    this.setData(changed)
  },

  // 公司地址输入
  addressInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['FormList[6].content'] = e.detail.value
    this.setData(changed)
  },

  // 文字简介输入
  introduceInputChange: function (e) {
    // console.log(e)
    let changed = new Object()
    changed['Introduce.content'] = e.detail.value
    this.setData(changed)
  },

  // 标签表单
  checkboxChange: function (e) {
    let checked = [...e.detail.value]
    const changed = {}
    const TagsList = [...this.data.TagsList]
    if (checked.length > 3) {
      checked.shift()
    }
    for (let i = 0; i < TagsList.length; i++) {
      if (checked.indexOf(TagsList[i].id.toString()) !== -1) {
        changed['TagsList[' + i + '].checked'] = true
        changed['TagsList[' + i + '].status'] = 1
      } else {
        changed['TagsList[' + i + '].checked'] = false
        changed['TagsList[' + i + '].status'] = 0
      }
    }
    this.setData(changed)
  },

  // 选择图片
  selectFile: function (e) {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        // if (e.currentTarget.dataset.type == 1){
        //   wx.navigateTo({
        //     url: '/pages/cutPicture/cutPicture?img=' + tempFilePaths,
        //   })
        // } else {
          that.ftpFile({
            type: e.currentTarget.dataset.type,
            src: tempFilePaths,
            uid: that.data.userInfo.id,
          })
        // }
      },
      complete(res) {
        // console.log(res)
      }
    })
  },

  // 选择视频
  selectVideo: function (e) {
    const that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        // console.log(res.tempFilePath)
        const tempFilePaths = res.tempFilePath
        that.ftpFile({
          type: e.currentTarget.dataset.type,
          src: tempFilePaths,
          uid: that.data.userInfo.id,
        })
      }
    })
  },

  // 照片选择图片
  selectFile1: function (e) {
    const that = this
    wx.chooseImage({
      count: 8, // 默认9  
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有 
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        if (res.tempFilePaths.length > 0) {
          var imglen = that.data.Pictuer.srcList.length;
          //图如果满了9张，不显示加图
          if (imglen + res.tempFilePaths.length < 9) {
            //把每次选择的图push进数组
            for (let i = 0; i < res.tempFilePaths.length; i++) {
              that.ftpFile({
                type: e.currentTarget.dataset.type,
                src: res.tempFilePaths[i],
                uid: that.data.userInfo.id,
              })
            }
          } else {
            wx.showModal({
              title: '提示',
              content: '最多八张图片'
            })
            return;
          }
        }
      }
    })
    
  },

  // 选择图片
  selectFileVideo: function (e) {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        // if (e.currentTarget.dataset.type == 1){
        //   wx.navigateTo({
        //     url: '/pages/cutPicture/cutPicture?img=' + tempFilePaths,
        //   })
        // } else {
        that.ftpFile({
          type: e.currentTarget.dataset.type,
          src: tempFilePaths,
          uid: that.data.userInfo.id,
        })
        // }
      },
      complete(res) {
        // console.log(res)
      }
    })
  },

  // 文件提交
  ftpFile: function (params) {
    const that = this
    wx.showLoading({
      title: '上传中',
    })
    
    if(params.src==''){
      app.showTipMsg('请上传文件');
      return false;
    }
    wx.uploadFile({
      url: baseUrl + ftp_file, // 仅为示例，非真实的接口地址
      filePath: params.src,
      name: 'file',
      formData: {
        uid: params.uid,
        type: params.type,
        length: params.length
      },
      success(res) {
        wx.hideLoading();
        let json_res = JSON.parse(res.data)
        if (json_res.msg != "success") {
          app.showTipMsg(json_res.msg);
        } else {
          let changed = {}
          switch (Number(params.type)) {
            case 1:
              changed['ProfilePicture.type'] = 1
              changed['ProfilePicture.src'] = json_res.data.url
              that.setData(changed)
              break;

            case 2:
              changed['Video.type'] = 1
              changed['Video.src'] = json_res.data.url
              that.setData(changed)
              break;

            case 3:
              let { Pictuer } = that.data

              Pictuer.srcList.push({
                img_url: json_res.data.url,
                id: json_res.data.id
              });
              changed['Pictuer.type'] = 1
              changed['Pictuer.srcList'] = Pictuer.srcList
              that.setData(changed)
              break;

            case 4:
              changed['CompanyLogo.type'] = 1
              changed['CompanyLogo.src'] = json_res.data.url
              that.setData(changed)
              break;

            case 5:
              changed['Recorder.type'] = 2
              changed['Recorder.src'] = json_res.data.url
              that.setData(changed)
              break;
            case 6:
              changed['Videoimg.type'] = 1
              changed['Videoimg.src'] = json_res.data.url
              that.setData(changed)
              break;

            default:
              break;
          }
          // console.log(changed)
        }
      },
      fail(err) {
        wx.hideLoading();
        console.log(err)
      }
    })
  },

  // 删除文件
  deleteFile: function (e) {
    const that = this
    let params = {
      uid: that.data.userInfo.id,
      type: e.del_type ? e.del_type : e.currentTarget.dataset.type
    }
    app.HttpGetSend(
      del_file, {
        ...params
      },
      function (res) {
        // console.log(res)
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          let changed = {}
          switch (Number(params.type)) {
            case 1:
              changed['ProfilePicture.type'] = 0
              changed['ProfilePicture.src'] = ''
              that.setData(changed)
              break;

            case 2:
              changed['Video.type'] = 0
              changed['Video.src'] = ''
              that.setData(changed)
              break;

            // case 3:
            //   changed['Pictuer.type'] = 0
            //   changed['Pictuer.srcList'] = ''
            //   that.setData(changed)
            //   break;

            case 4:
              changed['CompanyLogo.type'] = 0
              changed['CompanyLogo.src'] = ''
              that.setData(changed)
              break;

            case 5:
              changed['Recorder.type'] = 0
              changed['Recorder.src'] = ''
              changed['Recorder.temp'] = ''
              that.setData(changed)
              break;
            case 6:
              changed['Videoimg.type'] = 0
              changed['Videoimg.src'] = ''
              that.setData(changed)
              break;

            default:
              break;
          }
          // console.log(changed)
        }
      })
  },

  // 删除用户个人图片
  delUserImg: function (e) {
    // console.log(e)
    const that = this
    const id = e.currentTarget.dataset.id
    const idx = e.currentTarget.dataset.idx
    app.HttpGetSend(
      del_user_img, {
        uid: that.data.userInfo.id,
        id: id
      },
      function (res) {
        // console.log(res)
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          let changed = new Object()
          let { Pictuer } = that.data
          if (Pictuer.srcList.length > 1) {
            Pictuer.srcList.splice(idx, 1);
            changed['Pictuer.srcList'] = Pictuer.srcList
          } else {
            changed['Pictuer.type'] = 0
            changed['Pictuer.srcList'] = []
          }
          that.setData(changed)
          // console.log(changed)
        }
      })
  },

  // 开始录音
  startRecorder: function () {
    const that = this
    console.log(recorderManager)
    recorderManager.start()
    recorderManager.onStart(res => {
      console.log('recorder start')
      that.setData({
        TaskShow: 1
      })
    })
  },

  // 结束录音
  stopRecorder: function () {
    const that = this
    recorderManager.stop()
    recorderManager.onStop(res => {
      // console.log(res)
      let changed = {}
      changed['TaskShow'] = 0
      changed['Recorder.type'] = 1
      changed['Recorder.src'] = ''
      changed['Recorder.temp'] = res.tempFilePath
      innerAudioContext.src = res.tempFilePath
      changed['Recorder.duration'] = getTimeSeconds(res.duration)
      that.setData(changed)
      wx.showModal({
        content: '上传录音',
        success(res) {
          if (res.confirm) {
            // console.log('用户点击确定')
            console.log('duration:', changed['Recorder.duration'])
            that.upRecorder(changed['Recorder.duration'])
          } else if (res.cancel) {
            // console.log('用户点击取消')
            let changed = {}
            changed['TaskShow'] = 0
            changed['Recorder.type'] = 0
            changed['Recorder.src'] = ''
            changed['Recorder.temp'] = ''
            that.setData(changed)
          }
        },
        fail() {

        }
      })
    })
  },

  // 删除录音
  delRecorder: function () {
    const that = this
    this.deleteFile({
      del_type: 5
    })
  },

  // 录音上传
  upRecorder: function (len) {
    console.log('录音上传:', len)
    const that = this
    this.ftpFile({
      type: 5,
      src: that.data.Recorder.temp,
      uid: that.data.userInfo.id,
      length: len
    })
  },

  // 开始播放录音
  startPlay: function () {
    const that = this
    // console.log(innerAudioContext.src)
    innerAudioContext.play()
    innerAudioContext.onPlay(res => {
      console.log('recorder play start')
      let changed = new Object()
      changed['Recorder.playStatus'] = 1
      that.setData(changed)
    })

    innerAudioContext.onEnded(res => {
      console.log('recorder onEnded start')
      let changed = new Object()
      changed['Recorder.playStatus'] = 2
      that.setData(changed)
    })
  },

  // 结束播放录音
  stopPlay: function () {
    console.log('结束播放')
    const that = this
    innerAudioContext.stop()
    innerAudioContext.onStop(res => {
      console.log('tap stop')
      let changed = new Object()
      changed['Recorder.playStatus'] = 2
      that.setData(changed)
    })
  },

  // 表单提交
  formSubmit: function (e) {
    // console.log(e)
    const that = this
    // 验证字段的规则
    const rules = {
      name: {
        required: true,
      },
      position: {
        required: true,
      },
      company: {
        required: true,
      },
      mobile: {
        required: true,
        tel: true,
      },
      email: {
        required: true,
        email: true,
      },
      address: {
        required: true,
      },
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      name: {
        required: '请填写姓名',
      },
      position: {
        required: '请填写职位',
      },
      company: {
        required: '请填写所属公司',
      },
      mobile: {
        required: '请填写联系方式',
        tel: '请输入正确的手机号',
      },
      email: {
        required: '请填写邮箱地址',
        email: '请输入正确的邮箱',
      },
      address: {
        required: '请填写地址',
      },
    }

    // 创建实例对象
    let formWxValidate = new WxValidate(rules, messages)

    //报错 
    let errModal = (error) => {
      wx.showModal({
        content: error.msg,
        showCancel: false,
      })
    }

    let params = {
      ...e.detail.value
    }
    params.flags = params.flagsArr.join(',')
    delete params.flagsArr
    try {
      if (!formWxValidate.checkForm(params)) {
        const error = formWxValidate.errorList[0]
        // console.log(error)
        errModal(error)
        return false
      } else {
        let CompanyLogo = that.data.CompanyLogo
        let ProfilePicture = that.data.ProfilePicture
        if (CompanyLogo.type == 0) {
          errModal({
            msg: '请上传公司Logo'
          })
        } else if (ProfilePicture.type == 0) {
          errModal({
            msg: '请上传个人形象照'
          })
        } else {
          app.showTipMsg("保存成功")
          var param = {
            timestamp: new Date().getTime(),
            uid: that.data.userInfo.id,
            ...params
          }
          param.sign = app.getSign(param)
          app.HttpGetSend(
            update_userInfo_v4, param,
            function (res) {
              // console.log(res)
              if (res.msg != "success") {
                app.showTipMsg(res.msg);
              } else {
                wx.switchTab({
                  url: '/pages/person/person',
                })
              }
            })
        }
      }
    } catch (error) {
      console.log(error)
    }
  },

  // 页面onhide提交
  formSubmitOnhide: function () {
    // console.log(e)
    const that = this
    const FormList = this.data.FormList
    const Introduce = this.data.Introduce
    const TagsList = this.data.TagsList
    let checkNullEmptyUndefined = (aim) => {
      // console.log(typeof (aim) != 'undefined')
      // console.log(aim != 'undefined')
      if (aim != '' && aim != null && typeof (aim) != 'undefined' && aim != 'undefined') {
        return true
      } else {
        return false
      }
    }


    let params = new Object()
    for (let i = 0; i < FormList.length; i++) {
      params[FormList[i].name] = ''
      if (checkNullEmptyUndefined(FormList[i].content)) {
        params[FormList[i].name] = FormList[i].content
      }
    }
    params[Introduce.name] = ''
    if (checkNullEmptyUndefined(Introduce.content)) {
      params[Introduce.name] = Introduce.content
    }
    let flagsArr = new Array()
    for (let i = 0; i < TagsList.length; i++) {
      if (TagsList[i].checked == true) {
        flagsArr.push(TagsList[i].id)
      }
    }
    if (flagsArr.length > 0) {
      params.flags = flagsArr.join(',')
    }
    try {
      var param = {
        timestamp: new Date().getTime(),
        uid: that.data.userInfo.id,
        ...params
      }
      param.sign = app.getSign(param)
      app.HttpGetSend(
        update_userInfo_v4, param ,
        function (res) {
          // console.log(res)
          if (res.msg != "success") {
            app.showTipMsg(res.msg);
          } else {

          }
        })

    } catch (error) {
      console.log(error)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.formSubmitOnhide()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})